# -*- coding: utf-8 -*-
"""
管理员云存储账号管理模块
包含云存储账号的增删改查功能
@api-version: 1.0.0
"""

from flask import request, g
from marshmallow import Schema, fields, ValidationError
from backend.models.user import User
from backend.models.cloud_storage_account import CloudStorageAccount
from backend.utils.response import success_response, error_response, validation_error_response, not_found_response
from backend.utils.auth import admin_required
from backend.utils.pagination import paginate_query
from backend.models import db
from datetime import datetime
import json
from . import admin_bp
from backend.clouds_sdk.cloud_factory import CloudFactory
from backend.clouds_sdk.client_cache_manager import get_cache_manager


# 定义请求验证Schema
class CloudAccountCreateSchema(Schema):
    cloudProvider = fields.String(required=True)
    cloudAccount = fields.String(required=True)
    cloudPassword = fields.String(required=True)
    cloudToken = fields.String(missing='')  # Token可选，创建时可能为空
    cloudTokenInfo = fields.Dict(missing={})  # Token信息可选
    rootDirectoryId = fields.String(missing='')  # 根目录ID可选
    storageQuota = fields.Integer(missing=10*1024*1024*1024)  # 默认10GB
    isActive = fields.Boolean(missing=True)
    cloudExpiresAt = fields.DateTime(missing=None)  # 过期时间可选


class CloudAccountUpdateSchema(Schema):
    cloudProvider = fields.String()  # 支持修改云存储提供商
    cloudAccount = fields.String()   # 支持修改云存储账号
    cloudPassword = fields.String()
    cloudToken = fields.String()
    cloudTokenInfo = fields.Dict()
    rootDirectoryId = fields.String()
    storageQuota = fields.Integer()
    isActive = fields.Boolean()
    isOnline = fields.Boolean()      # 支持手动设置在线状态
    cloudExpiresAt = fields.DateTime()


@admin_bp.route('/cloud-accounts', methods=['GET'])
@admin_required
def get_cloud_accounts():
    """获取云存储账号列表"""
    try:
        # 获取查询参数
        user_id = request.args.get('user_id', type=int)
        cloud_provider = request.args.get('cloud_provider', '').strip()
        is_active = request.args.get('is_active', type=lambda v: v.lower() == 'true' if v else None)
        search = request.args.get('search', '').strip()
        
        # 构建查询
        query = CloudStorageAccount.query
        
        # 用户ID筛选
        if user_id:
            query = query.filter_by(user_id=user_id)
        
        # 云存储提供商筛选
        if cloud_provider:
            query = query.filter_by(cloud_provider=cloud_provider)
        
        # 账号状态筛选
        if is_active is not None:
            query = query.filter_by(is_active=is_active)
        
        # 搜索条件
        if search:
            query = query.filter(CloudStorageAccount.cloud_account.like(f'%{search}%'))
        
        # 排序
        query = query.order_by(CloudStorageAccount.created_at.desc())
        
        # 分页
        pagination_data = paginate_query(query)
        
        # 转换数据格式，包含敏感信息（管理员可查看）
        accounts_data = [account.to_dict(include_sensitive=True) for account in pagination_data['items']]
        pagination_data['items'] = accounts_data
        
        return success_response(
            data=pagination_data,
            message='获取云存储账号列表成功'
        )
        
    except Exception as e:
        return error_response(f'获取云存储账号列表失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts/<int:id>', methods=['GET'])
@admin_required
def get_cloud_account(id):
    """获取单个云存储账号详情"""
    try:
        account = CloudStorageAccount.query.get(id)
        if not account:
            return not_found_response('云存储账号不存在')
        
        return success_response(
            data=account.to_dict(include_sensitive=True),
            message='获取云存储账号详情成功'
        )
        
    except Exception as e:
        return error_response(f'获取云存储账号详情失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts', methods=['POST'])
@admin_required
def create_cloud_account():
    """创建云存储账号"""
    try:
        # 数据验证
        schema = CloudAccountCreateSchema()
        try:
            data = schema.load(request.get_json() or {})
        except ValidationError as e:
            return validation_error_response(e.messages)
        
        # 检查是否已存在相同的云存储账号
        existing_account = CloudStorageAccount.query.filter_by(
            cloud_provider=data['cloudProvider'],
            cloud_account=data['cloudAccount']
        ).first()
        
        if existing_account:
            return error_response('该云存储账号已存在', 400)
        
        # 处理过期时间
        cloud_expires_at = data.get('cloudExpiresAt')
        if not cloud_expires_at:
            # 如果没有提供过期时间，默认设置为一年后
            from datetime import timedelta
            cloud_expires_at = datetime.utcnow() + timedelta(days=365)
        
        # 创建云存储账号（不关联特定用户）
        cloud_token_info = json.dumps(data['cloudTokenInfo']) if data['cloudTokenInfo'] else '{}'
        
        account = CloudStorageAccount(
            cloud_provider=data['cloudProvider'],
            cloud_account=data['cloudAccount'],
            cloud_password=data['cloudPassword'],
            cloud_token=data['cloudToken'],
            cloud_token_info=cloud_token_info,
            root_directory_id=data['rootDirectoryId'],
            storage_quota=data['storageQuota'],
            is_active=data['isActive'],
            cloud_expires_at=cloud_expires_at,
            user_id=None  # 不关联特定用户
        )
        
        db.session.add(account)
        db.session.commit()
        
        return success_response(
            data=account.to_dict(include_sensitive=True),
            message='创建云存储账号成功'
        )
        
    except Exception as e:
        db.session.rollback()
        return error_response(f'创建云存储账号失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts/<int:id>', methods=['PUT'])
@admin_required
def update_cloud_account(id):
    """更新云存储账号"""
    try:
        # 检查账号是否存在
        account = CloudStorageAccount.query.get(id)
        if not account:
            return not_found_response('云存储账号不存在')
        
        # 检查是否有token信息
        if not account.cloud_token_info:
            return error_response('账号未登录，请先进行登录操作', 400)
        
        # 数据验证
        schema = CloudAccountUpdateSchema()
        try:
            data = schema.load(request.get_json() or {})
        except ValidationError as e:
            return validation_error_response(e.messages)
        
        # 检查是否修改了云存储账号，需要验证唯一性
        if 'cloudProvider' in data or 'cloudAccount' in data:
            new_provider = data.get('cloudProvider', account.cloud_provider)
            new_account = data.get('cloudAccount', account.cloud_account)
            
            # 检查是否与其他账号冲突
            existing_account = CloudStorageAccount.query.filter(
                CloudStorageAccount.id != id,
                CloudStorageAccount.cloud_provider == new_provider,
                CloudStorageAccount.cloud_account == new_account
            ).first()
            
            if existing_account:
                return error_response('该云存储账号已存在', 400)
        
        # 更新账号信息
        if 'cloudProvider' in data:
            account.cloud_provider = data['cloudProvider']
        
        if 'cloudAccount' in data:
            account.cloud_account = data['cloudAccount']
        
        if 'cloudPassword' in data:
            account.cloud_password = data['cloudPassword']
        
        if 'cloudToken' in data:
            account.cloud_token = data['cloudToken']
        
        if 'cloudTokenInfo' in data:
            account.cloud_token_info = json.dumps(data['cloudTokenInfo'])
        
        if 'rootDirectoryId' in data:
            account.root_directory_id = data['rootDirectoryId']
        
        if 'storageQuota' in data:
            account.storage_quota = data['storageQuota']
        
        if 'isActive' in data:
            account.is_active = data['isActive']
        
        if 'isOnline' in data:
            account.is_online = data['isOnline']
            account.last_check_at = datetime.utcnow()
        
        if 'cloudExpiresAt' in data:
            account.cloud_expires_at = data['cloudExpiresAt']
        
        db.session.commit()
        
        return success_response(
            data=account.to_dict(include_sensitive=True),
            message='更新云存储账号成功'
        )
        
    except Exception as e:
        db.session.rollback()
        return error_response(f'更新云存储账号失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts/<int:id>', methods=['DELETE'])
@admin_required
def delete_cloud_account(id):
    """删除云存储账号"""
    try:
        # 检查账号是否存在
        account = CloudStorageAccount.query.get(id)
        if not account:
            return not_found_response('云存储账号不存在')
        
        # 删除账号
        db.session.delete(account)
        db.session.commit()
        
        return success_response(
            data=None,
            message='删除云存储账号成功'
        )
        
    except Exception as e:
        db.session.rollback()
        return error_response(f'删除云存储账号失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts/<int:id>/login', methods=['POST'])
@admin_required
def login_cloud_account(id):
    """使用账号密码登录云存储账号"""
    try:
        # 检查账号是否存在
        account = CloudStorageAccount.query.get(id)
        if not account:
            return not_found_response('云存储账号不存在')
        
        # 调用云存储SDK进行登录
        from backend.clouds_sdk import CloudFactory
        import logging
        
        logger = logging.getLogger(__name__)
        logger.info(f"开始登录云存储账号 ID: {account.id}, 账号: {account.cloud_account}, 提供商: {account.cloud_provider}")
        print(f"[DEBUG] 开始登录云存储账号 ID: {account.id}, 账号: {account.cloud_account}, 提供商: {account.cloud_provider}")
        
        # 打印详细的账号信息
        print(f"[DEBUG] 登录账号详细信息:")
        print(f"[DEBUG]   - ID: {account.id}")
        print(f"[DEBUG]   - 云存储类型: {account.cloud_provider}")
        print(f"[DEBUG]   - 用户名: {account.cloud_account}")
        print(f"[DEBUG]   - 密码长度: {len(account.cloud_password) if account.cloud_password else 0}")
        print(f"[DEBUG]   - 当前在线状态: {account.is_online}")
        print(f"[DEBUG]   - 上次检测时间: {account.last_check_at}")
        print(f"[DEBUG]   - 是否有token信息: {bool(account.cloud_token_info)}")
        
        # 初始化登录结果
        is_online = False
        user_info = None
        error_message = None
        
        try:
            # 创建云盘客户端
            print(f"[DEBUG] 创建云盘客户端，类型: {account.cloud_provider}")
            logger.info(f"创建云盘客户端，类型: {account.cloud_provider}")
            
            print(f"[DEBUG] 调用CloudFactory.create_client参数:")
            print(f"[DEBUG]   - cloud_type: {account.cloud_provider}")
            print(f"[DEBUG]   - account_id: {account.id}")
            print(f"[DEBUG]   - username: {account.cloud_account}")
            print(f"[DEBUG]   - password: {'*' * len(account.cloud_password) if account.cloud_password else 'None'}")
            
            client = CloudFactory.create_client_for_login(
                cloud_type=account.cloud_provider,
                account_id=account.id,
                username=account.cloud_account,
                password=account.cloud_password
            )
            print(f"[DEBUG] 云盘客户端创建成功")
            logger.info("云盘客户端创建成功")
            
            # 使用账号密码进行登录
            print(f"[DEBUG] 开始使用账号密码登录...")
            print(f"[DEBUG] 调用client.login_with_credentials()...")
            logger.info("开始使用账号密码登录...")
            login_success = client.login_with_credentials()
            print(f"[DEBUG] login_with_credentials()返回结果: {login_success}")
            
            if login_success:
                print(f"[DEBUG] 登录成功")
                logger.info("登录成功")
                is_online = True
                
                # 获取用户信息
                try:
                    print(f"[DEBUG] 开始获取用户信息...")
                    user_info = client.get_user_info()
                    print(f"[DEBUG] 获取用户信息成功: {user_info}")
                    logger.info(f"获取用户信息成功: {user_info}")
                except Exception as e:
                    print(f"[DEBUG] 获取用户信息失败: {e}")
                    logger.warning(f"获取用户信息失败: {e}")
                    user_info = None
                
                # 保存token信息到数据库
                try:
                    print(f"[DEBUG] 开始获取token信息...")
                    token_info = client.get_token_info()
                    if token_info:
                        print(f"[DEBUG] 获取到token信息，包含字段: {list(token_info.keys()) if isinstance(token_info, dict) else 'not dict'}")
                        account.cloud_token_info = json.dumps(token_info)
                        print(f"[DEBUG] 保存token信息成功")
                        logger.info("保存token信息成功")
                    else:
                        print(f"[DEBUG] 未获取到token信息")
                except Exception as e:
                    print(f"[DEBUG] 保存token信息失败: {e}")
                    logger.warning(f"保存token信息失败: {e}")
            else:
                print(f"[DEBUG] 登录失败")
                logger.error("登录失败")
                error_message = "登录失败，请检查账号密码"
                
        except Exception as e:
            print(f"[DEBUG] 登录过程中发生异常: {e}")
            print(f"[DEBUG] 异常类型: {type(e).__name__}")
            import traceback
            print(f"[DEBUG] 异常堆栈: {traceback.format_exc()}")
            logger.error(f"登录过程中发生异常: {e}")
            error_message = str(e)
        
        # 更新账号状态
        print(f"[DEBUG] 更新账号状态...")
        account.is_online = is_online
        account.last_check_at = datetime.utcnow()
        
        if user_info:
            account.user_info = json.dumps(user_info)
            print(f"[DEBUG] 保存用户信息到数据库")
        
        if error_message:
            account.error_message = error_message
            print(f"[DEBUG] 保存错误信息到数据库: {error_message}")
        else:
            account.error_message = None
        
        # 记录token更新信息
        if token_updated:
            print(f"[DEBUG] token信息已更新并保存到数据库")
            logger.info("token信息已更新并保存到数据库")
        
        # 保存到数据库
        try:
            print(f"[DEBUG] 提交数据库事务...")
            db.session.commit()
            print(f"[DEBUG] 数据库更新成功")
            logger.info("数据库更新成功")
        except Exception as e:
            print(f"[DEBUG] 数据库更新失败: {e}")
            logger.error(f"数据库更新失败: {e}")
            db.session.rollback()
            return error_response(f'数据库更新失败: {str(e)}', 500)
        
        print(f"[DEBUG] 登录完成，最终结果:")
        print(f"[DEBUG]   - 在线状态: {is_online}")
        print(f"[DEBUG]   - 错误信息: {error_message}")
        print(f"[DEBUG]   - 用户信息: {user_info}")
        
        return success_response(
            data={
                'id': account.id,
                'is_online': is_online,
                'user_info': user_info,
                'error_message': error_message,
                'last_check_at': account.last_check_at.isoformat() if account.last_check_at else None
            },
            message='登录成功' if is_online else f'登录失败: {error_message}'
        )
        
    except Exception as e:
        print(f"[DEBUG] 登录云存储账号失败: {e}")
        import traceback
        print(f"[DEBUG] 异常堆栈: {traceback.format_exc()}")
        return error_response(f'登录云存储账号失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts/<int:id>/check', methods=['POST'])
@admin_required
def check_cloud_account(id):
    """智能检测云存储账号连接状态：先用token检测，未登录则用密码登录"""
    try:
        # 检查账号是否存在
        account = CloudStorageAccount.query.get(id)
        if not account:
            return not_found_response('云存储账号不存在')
        
        # 调用云存储SDK进行状态检测
        from backend.clouds_sdk import CloudFactory
        import logging
        
        logger = logging.getLogger(__name__)
        logger.info(f"开始智能检测云存储账号状态 ID: {account.id}, 账号: {account.cloud_account}, 提供商: {account.cloud_provider}")
        print(f"[DEBUG] 开始智能检测云存储账号状态 ID: {account.id}, 账号: {account.cloud_account}, 提供商: {account.cloud_provider}")
        
        # 打印详细的账号信息
        print(f"[DEBUG] 账号详细信息:")
        print(f"[DEBUG]   - ID: {account.id}")
        print(f"[DEBUG]   - 云存储类型: {account.cloud_provider}")
        print(f"[DEBUG]   - 用户名: {account.cloud_account}")
        print(f"[DEBUG]   - 密码长度: {len(account.cloud_password) if account.cloud_password else 0}")
        print(f"[DEBUG]   - 当前在线状态: {account.is_online}")
        print(f"[DEBUG]   - 上次检测时间: {account.last_check_at}")
        print(f"[DEBUG]   - 是否有token信息: {bool(account.cloud_token_info)}")
        if account.cloud_token_info:
            print(f"[DEBUG]   - token信息长度: {len(account.cloud_token_info)}")
        
        # 初始化检测结果
        is_online = False
        user_info = None
        error_message = None
        client = None
        token_updated = False
        
        try:
            # 第一步：尝试使用token检测登录状态
            if account.cloud_token_info:
                print(f"[DEBUG] 步骤1: 使用token检测登录状态")
                logger.info("步骤1: 使用token检测登录状态")
                
                try:
                    # 解析token信息
                    token_info = json.loads(account.cloud_token_info)
                    print(f"[DEBUG] token信息解析成功，包含字段: {list(token_info.keys()) if isinstance(token_info, dict) else 'not dict'}")
                    
                    # 使用token创建客户端
                    client = CloudFactory.create_client_with_token(
                        cloud_type=account.cloud_provider,
                        account_id=account.id,
                        username=account.cloud_account,
                        token_info=token_info
                    )
                    print(f"[DEBUG] 使用token创建客户端成功")
                    
                    # 检测登录状态
                    is_online = client.check_login_status_only()
                    print(f"[DEBUG] token登录状态检测结果: {is_online}")
                    
                    if is_online:
                        print(f"[DEBUG] token有效，账号已登录")
                        logger.info("token有效，账号已登录")
                    else:
                        print(f"[DEBUG] token无效或已过期，需要密码登录")
                        logger.info("token无效或已过期，需要密码登录")
                        
                except Exception as e:
                    print(f"[DEBUG] token检测失败: {e}")
                    logger.warning(f"token检测失败: {e}")
                    is_online = False
                    client = None
            else:
                print(f"[DEBUG] 无token信息，直接使用密码登录")
                logger.info("无token信息，直接使用密码登录")
            
            # 第二步：如果token检测失败，使用密码登录
            if not is_online:
                print(f"[DEBUG] 步骤2: 使用密码登录")
                logger.info("步骤2: 使用密码登录")
                
                if not account.cloud_password:
                    error_message = "账号密码为空，无法登录"
                    print(f"[DEBUG] {error_message}")
                    logger.error(error_message)
                else:
                    try:
                        # 使用密码创建客户端
                        client = CloudFactory.create_client(
                            cloud_type=account.cloud_provider,
                            account_id=account.id,
                            username=account.cloud_account,
                            password=account.cloud_password
                        )
                        print(f"[DEBUG] 使用密码创建客户端成功")
                        
                        # 尝试登录
                        login_result = client.login()
                        print(f"[DEBUG] 密码登录结果: {login_result}")
                        
                        if login_result:
                            is_online = True
                            print(f"[DEBUG] 密码登录成功")
                            logger.info("密码登录成功")
                            
                            # 获取新的token信息并保存到数据库
                            try:
                                new_token_info = client.get_token_info()
                                if new_token_info:
                                    account.cloud_token_info = json.dumps(new_token_info)
                                    token_updated = True
                                    print(f"[DEBUG] 获取并保存新token信息成功")
                                    logger.info("获取并保存新token信息成功")
                                else:
                                    print(f"[DEBUG] 未能获取token信息")
                                    logger.warning("未能获取token信息")
                            except Exception as e:
                                print(f"[DEBUG] 获取token信息失败: {e}")
                                logger.warning(f"获取token信息失败: {e}")
                        else:
                            error_message = "密码登录失败"
                            print(f"[DEBUG] {error_message}")
                            logger.error(error_message)
                            
                    except Exception as e:
                        error_message = f"密码登录过程中发生异常: {str(e)}"
                        print(f"[DEBUG] {error_message}")
                        logger.error(error_message)
            
            # 第三步：如果登录成功，初始化客户端缓存和获取用户信息
            if is_online and client:
                print(f"[DEBUG] 步骤3: 登录成功，初始化缓存和获取用户信息")
                logger.info("登录成功，初始化缓存和获取用户信息")
                
                # 将客户端添加到缓存管理器
                try:
                    print(f"[DEBUG] 将客户端添加到缓存管理器...")
                    cache_manager = get_cache_manager()
                    
                    # 准备账号信息，使用最新的token信息
                    current_token_info = None
                    if account.cloud_token_info:
                        try:
                            current_token_info = json.loads(account.cloud_token_info)
                        except:
                            current_token_info = None
                    
                    account_info = {
                        'id': account.id,
                        'cloud_provider': account.cloud_provider,
                        'cloud_account': account.cloud_account,
                        'cloud_password': account.cloud_password,
                        'token_info': current_token_info
                    }
                    
                    # 使用用户ID为0表示管理员账号，如果有实际用户ID可以传入
                    user_id = account.user_id or 0
                    cached_client = cache_manager.get_client(user_id, account_info, auto_login=False)
                    if cached_client:
                        print(f"[DEBUG] 客户端已成功添加到缓存管理器")
                        logger.info("客户端已成功添加到缓存管理器")
                    else:
                        print(f"[DEBUG] 添加客户端到缓存管理器失败")
                        logger.warning("添加客户端到缓存管理器失败")
                except Exception as e:
                    print(f"[DEBUG] 缓存客户端时发生异常: {e}")
                    logger.warning(f"缓存客户端时发生异常: {e}")
                
                # 获取用户信息
                try:
                    print(f"[DEBUG] 开始获取用户信息...")
                    user_info = client.get_user_info()
                    print(f"[DEBUG] 获取用户信息成功: {user_info}")
                    logger.info(f"获取用户信息成功: {user_info}")
                except Exception as e:
                    print(f"[DEBUG] 获取用户信息失败: {e}")
                    logger.warning(f"获取用户信息失败: {e}")
                    user_info = None
            else:
                print(f"[DEBUG] 登录失败，账号离线")
                logger.info("登录失败，账号离线")
                if not error_message:
                    error_message = "账号离线，请检查账号密码"
                
        except Exception as e:
            print(f"[DEBUG] 检测过程中发生异常: {e}")
            print(f"[DEBUG] 异常类型: {type(e).__name__}")
            import traceback
            print(f"[DEBUG] 异常堆栈: {traceback.format_exc()}")
            logger.error(f"检测过程中发生异常: {e}")
            error_message = str(e)
        
        # 更新账号状态
        print(f"[DEBUG] 更新账号状态...")
        account.is_online = is_online
        account.last_check_at = datetime.utcnow()
        
        if user_info:
            account.user_info = json.dumps(user_info)
            print(f"[DEBUG] 保存用户信息到数据库")
        
        if error_message:
            account.error_message = error_message
            print(f"[DEBUG] 保存错误信息到数据库: {error_message}")
        else:
            account.error_message = None
        
        # 保存到数据库
        try:
            print(f"[DEBUG] 提交数据库事务...")
            db.session.commit()
            print(f"[DEBUG] 数据库更新成功")
            logger.info("数据库更新成功")
        except Exception as e:
            print(f"[DEBUG] 数据库更新失败: {e}")
            logger.error(f"数据库更新失败: {e}")
            db.session.rollback()
            return error_response(f'数据库更新失败: {str(e)}', 500)
        
        print(f"[DEBUG] 检测完成，最终结果:")
        print(f"[DEBUG]   - 在线状态: {is_online}")
        print(f"[DEBUG]   - 错误信息: {error_message}")
        print(f"[DEBUG]   - 用户信息: {user_info}")
        print(f"[DEBUG]   - token已更新: {token_updated}")
        
        return success_response(
            data={
                'id': account.id,
                'is_online': is_online,
                'user_info': user_info,
                'error_message': error_message,
                'token_updated': token_updated,
                'last_check_at': account.last_check_at.isoformat() if account.last_check_at else None
            },
            message='检测成功' if is_online else f'检测失败: {error_message}'
        )
        
    except Exception as e:
        print(f"[DEBUG] 检测云存储账号失败: {e}")
        import traceback
        print(f"[DEBUG] 异常堆栈: {traceback.format_exc()}")
        return error_response(f'检测云存储账号失败: {str(e)}', 500)


# 原有的检测方法保持不变，用于兼容性
@admin_bp.route('/cloud-accounts/<int:id>/check-legacy', methods=['POST'])
@admin_required
def check_cloud_account_legacy(id):
    """检测云存储账号连接状态（原有方法，包含自动登录）"""
    try:
        # 检查账号是否存在
        account = CloudStorageAccount.query.get(id)
        if not account:
            return not_found_response('云存储账号不存在')
        
        # 调用云存储SDK进行连接测试
        from backend.clouds_sdk import CloudFactory
        import logging
        
        logger = logging.getLogger(__name__)
        logger.info(f"开始检测云存储账号 ID: {account.id}, 账号: {account.cloud_account}, 提供商: {account.cloud_provider}")
        
        # 初始化检测结果
        is_online = False
        user_info = None
        error_message = None
        
        try:
            # 创建云盘客户端
            print(f"[DEBUG] 创建云盘客户端，类型: {account.cloud_provider}")
            logger.info(f"创建云盘客户端，类型: {account.cloud_provider}")
            client = CloudFactory.create_client(
                cloud_type=account.cloud_provider,
                account_id=account.id,
                username=account.cloud_account,
                password=account.cloud_password
            )
            print(f"[DEBUG] 云盘客户端创建成功")
            logger.info("云盘客户端创建成功")
            
            # 检查登录状态
            print(f"[DEBUG] 检查登录状态...")
            logger.info("检查登录状态...")
            is_online = client.is_login()
            print(f"[DEBUG] 登录状态检查结果: {is_online}")
            logger.info(f"登录状态检查结果: {is_online}")
            
            if not is_online:
                # 如果登录状态无效，尝试重新登录
                print(f"[DEBUG] 登录状态无效，尝试重新登录...")
                logger.info("登录状态无效，尝试重新登录...")
                login_success = client.login()
                print(f"[DEBUG] 重新登录结果: {login_success}")
                logger.info(f"重新登录结果: {login_success}")
                if login_success:
                    is_online = True
                    # 获取用户信息
                    print(f"[DEBUG] 获取用户信息...")
                    logger.info("获取用户信息...")
                    user_info = client.get_user_info()
                    if user_info:
                        print(f"[DEBUG] 用户信息: {user_info}")
                        logger.info(f"用户信息: {user_info}")
                else:
                    print(f"[DEBUG] 重新登录失败")
                    logger.warning("重新登录失败")
            else:
                # 如果已登录，获取用户信息
                user_info = client.get_user_info()
                
        except Exception as sdk_error:
            # SDK调用失败
            print(f"[DEBUG] SDK调用失败: {str(sdk_error)}")
            logger.error(f"SDK调用失败: {str(sdk_error)}", exc_info=True)
            is_online = False
            error_message = str(sdk_error)
        
        # 在API层面更新数据库状态（与SDK分离）
        try:
            # 更新账号在线状态
            account.update_online_status(is_online)
            
            # 如果获取到用户信息，更新相关字段
            if user_info:
                if 'quota' in user_info:
                    account.storage_quota = user_info.get('quota', account.storage_quota)
                if 'rootDirectoryId' in user_info:
                    account.root_directory_id = user_info.get('rootDirectoryId', account.root_directory_id)
            
            db.session.commit()
            
            # 构建响应数据
            response_data = {
                'id': account.id,
                'isOnline': account.is_online,
                'lastCheckAt': account.last_check_at.isoformat() if account.last_check_at else None,
                'statusDisplay': account.get_status_display()
            }
            
            if error_message:
                response_data['error'] = error_message
                return success_response(
                    data=response_data,
                    message=f'云存储账号检测完成，但连接失败: {error_message}'
                )
            else:
                return success_response(
                    data=response_data,
                    message='云存储账号检测完成'
                )
                
        except Exception as db_error:
            db.session.rollback()
            logger.error(f"数据库更新失败: {str(db_error)}", exc_info=True)
            return error_response(f'检测完成但状态更新失败: {str(db_error)}', 500)
        
    except Exception as e:
        db.session.rollback()
        return error_response(f'检测云存储账号失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts/check-today', methods=['POST'])
@admin_required
def check_today_cloud_accounts():
    """检测当天添加的云存储账号连接状态"""
    try:
        from datetime import date
        from backend.clouds_sdk import CloudFactory
        
        # 获取当天添加的账号
        today = date.today()
        today_accounts = CloudStorageAccount.query.filter(
            db.func.date(CloudStorageAccount.created_at) == today
        ).all()
        
        if not today_accounts:
            return success_response(
                data={'checked_count': 0, 'results': []},
                message='今天没有新添加的云存储账号'
            )
        
        results = []
        checked_count = 0
        
        for account in today_accounts:
            # 初始化检测结果
            is_online = False
            user_info = None
            error_message = None
            
            try:
                # 创建云盘客户端
                client = CloudFactory.create_client(
                    cloud_type=account.cloud_provider,
                    account_id=account.id,
                    username=account.cloud_account,
                    password=account.cloud_password
                )
                
                # 检查登录状态
                is_online = client.is_login()
                
                if not is_online:
                    # 如果登录状态无效，尝试重新登录
                    login_success = client.login()
                    if login_success:
                        is_online = True
                        # 获取用户信息
                        user_info = client.get_user_info()
                else:
                    # 如果已登录，获取用户信息
                    user_info = client.get_user_info()
                
            except Exception as sdk_error:
                # SDK调用失败
                is_online = False
                error_message = str(sdk_error)
            
            # 在API层面更新数据库状态（与SDK分离）
            try:
                # 更新账号在线状态
                account.update_online_status(is_online)
                
                # 如果获取到用户信息，更新相关字段
                if user_info:
                    if 'quota' in user_info:
                        account.storage_quota = user_info.get('quota', account.storage_quota)
                    if 'rootDirectoryId' in user_info:
                        account.root_directory_id = user_info.get('rootDirectoryId', account.root_directory_id)
                
                checked_count += 1
                
                # 构建结果数据
                result_data = {
                    'id': account.id,
                    'cloudAccount': account.cloud_account,
                    'cloudProvider': account.cloud_provider,
                    'isOnline': is_online,
                    'lastCheckAt': account.last_check_at.isoformat() if account.last_check_at else None,
                    'statusDisplay': account.get_status_display(),
                    'success': not error_message
                }
                
                if error_message:
                    result_data['error'] = error_message
                
                results.append(result_data)
                
            except Exception as db_error:
                # 数据库更新失败，但继续检测其他账号
                checked_count += 1
                results.append({
                    'id': account.id,
                    'cloudAccount': account.cloud_account,
                    'cloudProvider': account.cloud_provider,
                    'isOnline': False,
                    'lastCheckAt': None,
                    'statusDisplay': '更新失败',
                    'success': False,
                    'error': f'数据库更新失败: {str(db_error)}'
                })
        
        # 提交所有更新
        db.session.commit()
        
        return success_response(
            data={
                'checked_count': checked_count,
                'total_count': len(today_accounts),
                'results': results
            },
            message=f'当天云存储账号检测完成，共检测 {checked_count} 个账号'
        )
        
    except Exception as e:
        db.session.rollback()
        return error_response(f'检测当天云存储账号失败: {str(e)}', 500)


@admin_bp.route('/users/<int:user_id>/cloud-accounts', methods=['GET'])
@admin_required
def get_user_cloud_accounts(user_id):
    """获取用户的云存储账号列表"""
    try:
        # 检查用户是否存在
        user = User.query.get(user_id)
        if not user:
            return not_found_response('用户不存在')
        
        # 构建查询
        query = CloudStorageAccount.query.filter_by(user_id=user_id)
        
        # 排序
        query = query.order_by(CloudStorageAccount.created_at.desc())
        
        # 分页
        pagination_data = paginate_query(query)
        
        # 转换数据格式，包含敏感信息（管理员可查看）
        accounts_data = [account.to_dict(include_sensitive=True) for account in pagination_data['items']]
        pagination_data['items'] = accounts_data
        
        return success_response(
            data=pagination_data,
            message='获取用户云存储账号列表成功'
        )
        
    except Exception as e:
        return error_response(f'获取用户云存储账号列表失败: {str(e)}', 500)


# 文件操作相关API
class FileOperationSchema(Schema):
    path = fields.String(missing='/')  # 文件路径，默认根目录
    folder_name = fields.String()  # 文件夹名称
    new_name = fields.String()  # 新名称
    target_path = fields.String()  # 目标路径


@admin_bp.route('/cloud-accounts/<int:id>/files', methods=['GET'])
@admin_required
def get_cloud_files(id):
    """获取云存储账号的文件列表"""
    import logging
    logger = logging.getLogger(__name__)
    
    try:
        logger.info(f"开始获取云存储文件列表 - 账号ID: {id}")
        print(f"[DEBUG] 开始获取云存储文件列表 - 账号ID: {id}")
        
        # 获取云存储账号
        account = CloudStorageAccount.query.get(id)
        if not account:
            print(f"[DEBUG] 云存储账号不存在 - ID: {id}")
            return not_found_response('云存储账号不存在')
        
        # 获取路径参数
        path = request.args.get('path', '/')
        
        # 打印详细的账号信息
        print(f"[DEBUG] 账号详细信息:")
        print(f"[DEBUG]   - ID: {account.id}")
        print(f"[DEBUG]   - 云存储类型: {account.cloud_provider}")
        print(f"[DEBUG]   - 用户名: {account.cloud_account}")
        print(f"[DEBUG]   - 当前在线状态: {account.is_online}")
        print(f"[DEBUG]   - 是否有token信息: {bool(account.cloud_token_info)}")
        print(f"[DEBUG]   - 请求路径: {path}")
        
        # 检查账号是否在线
        if not account.is_online:
            print(f"[DEBUG] 账号离线状态，无法获取文件列表")
            return error_response('账号未登录，请先登录后再查看文件', 400)
        
        # 检查是否有token信息
        if not account.cloud_token_info:
            print(f"[DEBUG] 账号没有token信息，无法获取文件列表")
            return error_response('账号缺少认证信息，请重新登录', 400)
        
        # 解析token信息
        try:
            print(f"[DEBUG] 开始解析token信息...")
            token_info = json.loads(account.cloud_token_info) if isinstance(account.cloud_token_info, str) else account.cloud_token_info
            print(f"[DEBUG] token信息解析成功，包含字段: {list(token_info.keys()) if isinstance(token_info, dict) else 'not dict'}")
        except Exception as e:
            print(f"[DEBUG] 解析token信息失败: {e}")
            logger.error(f"解析token信息失败: {e}")
            return error_response(f'token信息格式错误: {str(e)}', 400)
        
        # 创建云盘客户端
        print(f"[DEBUG] 调用CloudFactory.create_client_with_token参数:")
        print(f"[DEBUG]   - cloud_type: {account.cloud_provider}")
        print(f"[DEBUG]   - account_id: {account.id}")
        print(f"[DEBUG]   - token_info: {list(token_info.keys()) if isinstance(token_info, dict) else 'not dict'}")
        
        client = CloudFactory.create_client_with_token(
            cloud_type=account.cloud_provider,
            account_id=account.id,
            username=account.cloud_account,
            token_info=token_info
        )
        print(f"[DEBUG] 云盘客户端创建成功")
        logger.info("云盘客户端创建成功")
        
        # 获取文件列表
        print(f"[DEBUG] 开始获取文件列表...")
        print(f"[DEBUG] 调用client.get_files(path='{path}')...")
        logger.info(f"开始获取文件列表，路径: {path}")
        
        files = client.get_files(path)
        
        print(f"[DEBUG] 获取文件列表成功，文件数量: {len(files) if isinstance(files, list) else 'unknown'}")
        logger.info(f"获取文件列表成功，文件数量: {len(files) if isinstance(files, list) else 'unknown'}")
        
        # 打印文件列表概要
        if isinstance(files, list) and files:
            print(f"[DEBUG] 文件列表前3项:")
            for i, file_item in enumerate(files[:3]):
                if isinstance(file_item, dict):
                    print(f"[DEBUG]   {i+1}. {file_item.get('name', 'unknown')} ({file_item.get('type', 'unknown')})")
        
        return success_response(
            data={
                'files': files,
                'current_path': path,
                'account_id': id,
                'account_info': {
                    'cloud_provider': account.cloud_provider,
                    'cloud_account': account.cloud_account,
                    'is_online': account.is_online
                }
            },
            message='获取文件列表成功'
        )
        
    except Exception as e:
        print(f"[DEBUG] 获取文件列表失败: {e}")
        import traceback
        print(f"[DEBUG] 异常堆栈: {traceback.format_exc()}")
        logger.error(f"获取文件列表失败: {e}", exc_info=True)
        return error_response(f'获取文件列表失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts/<int:id>/folders', methods=['POST'])
@admin_required
def create_cloud_folder(id):
    """创建文件夹"""
    try:
        # 验证请求数据
        schema = FileOperationSchema()
        try:
            data = schema.load(request.json)
        except ValidationError as err:
            return validation_error_response(err.messages)
        
        # 获取云存储账号
        account = CloudStorageAccount.query.get(id)
        if not account:
            return not_found_response('云存储账号不存在')
        
        # 创建云盘客户端
        client = CloudFactory.create_client(
            cloud_type=account.cloudProvider,
            username=account.cloudAccount,
            password=account.cloudPassword
        )
        
        # 设置token信息
        if account.cloudTokenInfo:
            client.set_token_info(account.cloudTokenInfo)
        
        # 创建文件夹
        result = client.create_folder(
            parent_path=data.get('path', '/'),
            folder_name=data['folder_name']
        )
        
        return success_response(
            data=result,
            message='创建文件夹成功'
        )
        
    except Exception as e:
        return error_response(f'创建文件夹失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts/<int:id>/files', methods=['DELETE'])
@admin_required
def delete_cloud_file(id):
    """删除文件或文件夹"""
    try:
        # 验证请求数据
        schema = FileOperationSchema()
        try:
            data = schema.load(request.json)
        except ValidationError as err:
            return validation_error_response(err.messages)
        
        # 获取云存储账号
        account = CloudStorageAccount.query.get(id)
        if not account:
            return not_found_response('云存储账号不存在')
        
        # 创建云盘客户端
        client = CloudFactory.create_client(
            cloud_type=account.cloudProvider,
            username=account.cloudAccount,
            password=account.cloudPassword
        )
        
        # 设置token信息
        if account.cloudTokenInfo:
            client.set_token_info(account.cloudTokenInfo)
        
        # 删除文件或文件夹
        file_path = data['path']
        if file_path.endswith('/'):
            # 删除文件夹
            result = client.delete_folder(file_path)
        else:
            # 删除文件
            result = client.delete_file(file_path)
        
        return success_response(
            data=result,
            message='删除成功'
        )
        
    except Exception as e:
        return error_response(f'删除失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts/<int:id>/files/move', methods=['POST'])
@admin_required
def move_cloud_file(id):
    """移动文件或文件夹"""
    try:
        # 验证请求数据
        schema = FileOperationSchema()
        try:
            data = schema.load(request.json)
        except ValidationError as err:
            return validation_error_response(err.messages)
        
        # 获取云存储账号
        account = CloudStorageAccount.query.get(id)
        if not account:
            return not_found_response('云存储账号不存在')
        
        # 创建云盘客户端
        client = CloudFactory.create_client(
            cloud_type=account.cloudProvider,
            username=account.cloudAccount,
            password=account.cloudPassword
        )
        
        # 设置token信息
        if account.cloudTokenInfo:
            client.set_token_info(account.cloudTokenInfo)
        
        # 移动文件
        result = client.move_file(
            source_path=data['path'],
            target_path=data['target_path']
        )
        
        return success_response(
            data=result,
            message='移动成功'
        )
        
    except Exception as e:
        return error_response(f'移动失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts/<int:id>/files/copy', methods=['POST'])
@admin_required
def copy_cloud_file(id):
    """复制文件或文件夹"""
    try:
        # 验证请求数据
        schema = FileOperationSchema()
        try:
            data = schema.load(request.json)
        except ValidationError as err:
            return validation_error_response(err.messages)
        
        # 获取云存储账号
        account = CloudStorageAccount.query.get(id)
        if not account:
            return not_found_response('云存储账号不存在')
        
        # 创建云盘客户端
        client = CloudFactory.create_client(
            cloud_type=account.cloudProvider,
            username=account.cloudAccount,
            password=account.cloudPassword
        )
        
        # 设置token信息
        if account.cloudTokenInfo:
            client.set_token_info(account.cloudTokenInfo)
        
        # 复制文件
        result = client.copy_file(
            source_path=data['path'],
            target_path=data['target_path']
        )
        
        return success_response(
            data=result,
            message='复制成功'
        )
        
    except Exception as e:
        return error_response(f'复制失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts/<int:id>/files/rename', methods=['POST'])
@admin_required
def rename_cloud_file(id):
    """重命名文件或文件夹"""
    try:
        # 验证请求数据
        schema = FileOperationSchema()
        try:
            data = schema.load(request.json)
        except ValidationError as err:
            return validation_error_response(err.messages)
        
        # 获取云存储账号
        account = CloudStorageAccount.query.get(id)
        if not account:
            return not_found_response('云存储账号不存在')
        
        # 创建云盘客户端
        client = CloudFactory.create_client(
            cloud_type=account.cloudProvider,
            username=account.cloudAccount,
            password=account.cloudPassword
        )
        
        # 设置token信息
        if account.cloudTokenInfo:
            client.set_token_info(account.cloudTokenInfo)
        
        # 重命名文件
        file_path = data['path']
        if file_path.endswith('/'):
            # 重命名文件夹
            result = client.rename_folder(file_path, data['new_name'])
        else:
            # 重命名文件
            result = client.rename_file(file_path, data['new_name'])
        
        return success_response(
            data=result,
            message='重命名成功'
        )
        
    except Exception as e:
        return error_response(f'重命名失败: {str(e)}', 500)


@admin_bp.route('/cloud-accounts/<int:id>/files/upload', methods=['POST'])
@admin_required
def upload_cloud_file(id):
    """上传文件"""
    try:
        # 获取云存储账号
        account = CloudStorageAccount.query.get(id)
        if not account:
            return not_found_response('云存储账号不存在')
        
        # 获取上传的文件
        if 'file' not in request.files:
            return error_response('没有选择文件', 400)
        
        file = request.files['file']
        if file.filename == '':
            return error_response('文件名不能为空', 400)
        
        # 获取上传路径
        upload_path = request.form.get('path', '/')
        
        # 创建云盘客户端
        client = CloudFactory.create_client(
            cloud_type=account.cloudProvider,
            username=account.cloudAccount,
            password=account.cloudPassword
        )
        
        # 设置token信息
        if account.cloudTokenInfo:
            client.set_token_info(account.cloudTokenInfo)
        
        # 上传文件
        result = client.upload_file(
            local_file_path=file,
            remote_path=upload_path,
            filename=file.filename
        )
        
        return success_response(
            data=result,
            message='上传文件成功'
        )
        
    except Exception as e:
        return error_response(f'上传文件失败: {str(e)}', 500)